<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class User extends Base
{

    /**
     * User模型对象
     * @var \app\admin\model\vppz\User
     */
    protected $model = null;

	protected $searchFields = ['id','nickname','mobile'];
	protected $multiFields = ['black_switch'];


    public function _initialize()
    {
        parent::_initialize();
        $this->vipmodel = new \app\admin\model\vppz\VipPackage();
        $this->model = new \app\admin\model\vppz\User;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

/**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);
        $result = false;
        try {
            //保存医院
                //保存医院
                $data=array(
					'nickname'=>$form['nickname'],
					'avatar'=>$form['avatar'],
					'mobile'=>$form['mobile'],
					'is_vip'=>$form['is_vip'],
					'expire_time'=>$form['expire_time']
				);
				$ret=$this->model->where('id','=',$row['id'])->update($data);
                if(empty($ret)){
                    $result = false;
					$this->error('服务器刚刚走神了，重试看看呢');
				}
                $result = true;
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();

    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			// TODO 使快速搜索框支持查询加密UID，但是导致一个BUG即快速搜索与精确搜索同时时，以快速搜索的OR条件为准，精确搜索条件无效，所以两个搜索不能同时使用
			$search = $this->request->request('search');
			$uidWhere=[];
			if($search && !is_numeric($search)){
				$uid = \addons\vppz\library\Vpower::pdecode($search);
				if($uid && intval($uid)>0){
					$uidWhere['user.id']=$uid;
					// $this->model->whereOr('user.id',1); // 这样写不行,必须写在下面链式操作
				}
			}

			$adminAreasWhere=$this->adminAreasWhere('area_id');

            $list = $this->model
                    ->with(['area'])
                    ->where($where)->where($adminAreasWhere)->whereOr($uidWhere)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('area')->visible(['name']);
                if ($row['is_vip'] == 1){
                    $row['vip_status'] = '会员';
                }else{
                    $row['vip_status'] = '非会员';
                    $row['expire_time'] = '---';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function messageindex()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			// TODO 使快速搜索框支持查询加密UID，但是导致一个BUG即快速搜索与精确搜索同时时，以快速搜索的OR条件为准，精确搜索条件无效，所以两个搜索不能同时使用
			$search = $this->request->request('search');
			$uidWhere=[];
			if($search && !is_numeric($search)){
				$uid = \addons\vppz\library\Vpower::pdecode($search);
				if($uid && intval($uid)>0){
					$uidWhere['user.id']=$uid;
				}
			}

			$adminAreasWhere=$this->adminAreasWhere('area_id');

            $list = $this->model
                    ->with(['area'])
                    ->where($where)->whereNotNull('nickname')->where($adminAreasWhere)->whereOr($uidWhere)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('area')->visible(['name']);
                if ($row['is_vip'] == 1){
                    $row['vip_status'] = '会员';
                }else{
                    $row['vip_status'] = '非会员';
                    $row['expire_time'] = '---';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function messagefamilyindex()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			// TODO 使快速搜索框支持查询加密UID，但是导致一个BUG即快速搜索与精确搜索同时时，以快速搜索的OR条件为准，精确搜索条件无效，所以两个搜索不能同时使用
			$search = $this->request->request('search');
			$uidWhere=[];
			if($search && !is_numeric($search)){
				$uid = \addons\vppz\library\Vpower::pdecode($search);
				if($uid && intval($uid)>0){
					$uidWhere['user.id']=$uid;
				}
			}

			$adminAreasWhere=$this->adminAreasWhere('area_id');

            $list = $this->model
                    ->with(['area'])
                    ->where($where)->where(['is_vip'=>1])->whereNotNull('nickname')->where($adminAreasWhere)->whereOr($uidWhere)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('area')->visible(['name']);
                if ($row['is_vip'] == 1){
                    $row['vip_status'] = '会员';
                }else{
                    $row['vip_status'] = '非会员';
                    $row['expire_time'] = '---';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
public function openuservip(){
        $user_id = input('ids');
        $res = $this->vipmodel->whereNull('deletetime')->order('price','asc')->select();
        if(empty($res) === FALSE){
            foreach ($res as &$v){
                $v['duration'] = $v['duration'].'个月';
            }
        }
        if($this->request->isPost()){
            $package_id = input('package_id');
            if(empty($package_id)){
                $this->error('套餐选择有误');
            }
            $package = $this->vipmodel->where('id',$package_id)->find();
            if(empty($package)){
                $this->error('套餐选择有误');
            }
            $res = $this->model->where(['id'=>$user_id])->update(array(
                'is_vip'=>1,
                'vip_time'=>datetime(time(),'Y-m-d H:i:s'),
                'expire_time'=>datetime(strtotime("+".$package['duration']." months", time()),'Y-m-d H:i:s'),
            ));
            if($res){
                $this->success();
            }else{
                $this->error('操作失败，请重试');
            }
        }
        $this->assign('packages',$res);
        $this->assign('user_id',$user_id);
        return $this->view->fetch();
    }

public function xuqiuservip(){
        $user_id = input('ids');
        $res = $this->vipmodel->whereNull('deletetime')->order('price','asc')->select();
        if(empty($res) === FALSE){
            foreach ($res as &$v){
                $v['duration'] = $v['duration'].'个月';
            }
        }
        if($this->request->isPost()){
            $package_id = input('package_id');
            if(empty($package_id)){
                $this->error('套餐选择有误');
            }
            $package = $this->vipmodel->where('id',$package_id)->find();
            if(empty($package)){
                $this->error('套餐选择有误');
            }
            $user = $this->model->where(['id'=>$user_id])->find();
            $res = $this->model->where(['id'=>$user_id])->update(array(
                'is_vip'=>1,
                'expire_time'=>datetime(strtotime("+".$package['duration']." months", strtotime($user['expire_time'])),'Y-m-d H:i:s'),
            ));
            if($res){
                $this->success();
            }else{
                $this->error('操作失败，请重试');
            }
        }
        $this->assign('packages',$res);
        $this->assign('user_id',$user_id);
        return $this->view->fetch();
    }
    public function viplevel(){
        $result = ['total' => 2, 'rows' => array(
            array(
                'vip_level'=>0,
                'name'=>'普通会员'
            ),
            array(
                'vip_level'=>1,
                'name'=>'高级会员'
            ),
        )];
        return json($result);
    }
}
